/**  
 * 文 件 名: FileUtil.java  
 * 描    述：   
 * 版    权：Copyright (c)20012-2012 tongzhou All Rights Reserved.
 * 公    司: 同舟 
 * 作    者：彭定雄                     
 * 版    本: 1.0  
 * 创建时间: 2012-10-27
 *  
 * 修改历史：  
 * 时间                             作者                       版本                        描述  
 * ------------------------------------------------------------------  
 * 2012-10-27        彭定雄                1.0          1.0 Version  
 */

package com.tongzhou.util;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.struts2.ServletActionContext;

public class FileUtil {

	private static Logger log = Logger.getLogger(FileUtil.class.getName());

	//应用图标保存时的文件前缀名
	public final static String PREFIX_APP_ICON = "icon_";

	//上传文 件存放目录
	//上传文件存放根目录
	public final static String DIR_UPLOAD = "upload" + File.separator;
	//商城文件存放根目录
	public final static String DIR_STORE = DIR_UPLOAD + "store"
			+ File.separator;
	//第三方桌面应用存放跟目录
	public final static String DIR_UI = DIR_UPLOAD + "ui" + File.separator;
	//自有应用存放跟目录
	public final static String DIR_APP = DIR_UPLOAD + "app" + File.separator;
	//第三方桌面应用存APK包的目录
	public final static String DIR_UI_APP_APK = DIR_UI + "apk" + File.separator;
	//自有应用存APK包的目录
	public final static String DIR_APP_APP_APK = DIR_APP + "apk" + File.separator;
	//商城分类相关文件存放目录
	public final static String DIR_STORE_CATETORY = DIR_STORE + "category"
			+ File.separator;
	
	public final static String DIR_STORE_MUSIC = DIR_STORE + "music"
	+ File.separator;
	
	public final static String DIR_MUSIC_IMG = DIR_STORE_MUSIC + "img"
	+ File.separator;
	
	public final static String DIR_MUSIC_SONG = DIR_STORE_MUSIC + "mp3"
	+ File.separator;
	
	//商城应用相关文件存放目录
	public final static String DIR_STORE_APP = DIR_STORE + "app"
			+ File.separator;
	//商城客户端版本存放目录
	public final static String DIR_STORE_SELF_VER = DIR_STORE + "ver"
			+ File.separator;
	//存APK包的目录
	public final static String DIR_STORE_APP_APK = DIR_STORE_APP + "apk"
			+ File.separator;
	//存放应用相关图片的目录
	public final static String DIR_STORE_APP_IMAGES = DIR_STORE_APP + "images"
			+ File.separator;
	//专题相关文件存放目录
	public final static String DIR_STORE_TOPIC = DIR_STORE + "topic"
			+ File.separator;

	/**
	 * 取得应用根目录路径
	 *@author: 彭定雄
	 *@return
	 */
	public static String getWebRootDir() {
//		return ServletActionContext.getServletContext().getRealPath("");
		return ServletActionContext.getRequest().getRealPath("/");
		
	}

	/**
	 * 随机生成一个文 件名
	 *@author: 彭定雄
	 *@param prefix 文 件名前缀
	 *@return
	 */
	public static String generateFileName() {
		String name = new Date().getTime() + "";
		name += (int) (Math.random() * 10000);
		return name;
	}

	/**
	 * 根据文件名取得文件后缀名
	 *@author: 彭定雄
	 *@param fileName
	 *@return
	 */
	public static String getFileSuffix(String fileName) {
		if (fileName == null)
			return "";
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			return fileName.substring(index);
		} else {
			return "";
		}
	}

	/**
	 * 创建文件夹
	 *@author: 彭定雄
	 *@param dirPath
	 *@return
	 */
	public static boolean mkDir(String dirPath) {
		File file = new File(dirPath);
		if (!file.exists()) {
			return file.mkdirs();
		}
		return true;
	}

	/**
	 * 删除文件
	 *@author: 彭定雄
	 *@param filePath
	 *@return
	 */
	public static boolean removeFile(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			return file.delete();
		}
		return true;
	}

	/**
	 * 复制文件
	 *@author: 彭定雄
	 *@param srcFile
	 *@param destFile
	 *@return
	 */
	public static boolean copyFile(File srcFile, File destFile) {
		log.info("create file path:" + destFile.getPath() + " "
				+ destFile.getParent());
		//创建目标文件所在的目录
		mkDir(destFile.getParent());

		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			fos = new FileOutputStream(destFile);
			fis = new FileInputStream(srcFile);
			byte[] buffer = new byte[1024 * 1024];
			int length;
			while ((length = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return false;
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}

	public static BufferedImage resize(BufferedImage source, int targetW,
			int targetH, boolean isObs) {
		// targetW，targetH分别表示目标长和宽   
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		if (!isObs){
			//这里想实现在targetW，targetH范围内实现等比缩放。如果不需要等比缩放   
			//则将下面的if else语句注释即可   
			if (sx > sy) {
				sx = sy;
				targetW = (int) (sx * source.getWidth());
			} else {
				sy = sx;
				targetH = (int) (sy * source.getHeight());
			}
		}
		if (type == BufferedImage.TYPE_CUSTOM) { //handmade   
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
					targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
			target = new BufferedImage(targetW, targetH, type);
		Graphics2D g = target.createGraphics();
		//smoother than exlax:   
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}

	public static boolean resizeImage(String imageFile, int width, int height, boolean isObs) {
		BufferedImage srcImage;
		boolean flag = false;
		String imgType = "JPEG";
		if (imageFile.toLowerCase().endsWith(".png")) {
			imgType = "PNG";
		}
		File saveFile = new File(imageFile);
		File fromFile = new File(imageFile);
		try {
			srcImage = ImageIO.read(fromFile);
			int sourceWidth = srcImage.getWidth();
			int sourceHeight = srcImage.getHeight();
			if (width < sourceWidth || height < sourceHeight) {
				srcImage = resize(srcImage, width, height, isObs);
				ImageIO.write(srcImage, imgType, saveFile);
			}
			flag = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return flag;

	}
	
	/**
	 * 复制文件
	 *@author: 彭定雄
	 *@param srcFile
	 *@param srcName
	 *@return
	 */
	public static HSSFSheet readExcel(File srcFile) {
		FileInputStream fin;
		try {
			fin = new FileInputStream(srcFile);
			POIFSFileSystem fs = new POIFSFileSystem(fin);
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			HSSFSheet sheet = wb.getSheetAt(0);
			return sheet;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 复制文件
	 *@author: 彭定雄
	 *@param cell
	 *@return
	 */
	public static String getHSSFCellValue(HSSFCell cell) {
		if(cell==null){
			return "";
		}
		int type = cell.getCellType();
		switch (type) {
		case 3: // '\003'
			return "";

		case 4: // '\004'
			return String.valueOf(cell.getBooleanCellValue());

		case 2: // '\002'
			return String.valueOf(cell.getCellFormula());

		case 0: // '\0'
			return String.valueOf(cell.getNumericCellValue());
//			DecimalFormat myformat = new DecimalFormat("#");
//			double num = new Double((double)cell.getNumericCellValue());
//            return String.valueOf(myformat.format(num));

		case 1: // '\001'
		default:
			return cell.getStringCellValue();
		}
	}
	
	/**
	 * 复制文件-浮点型不适用科学计数法
	 *@author: 彭定雄
	 *@param cell
	 *@return
	 */
	public static String getHSSFCellValue2(HSSFCell cell) {
		if(cell==null){
			return "";
		}
		int type = cell.getCellType();
		switch (type) {
		case 3: // '\003'
			return "";

		case 4: // '\004'
			return String.valueOf(cell.getBooleanCellValue());

		case 2: // '\002'
			return String.valueOf(cell.getCellFormula());

		case 0: // '\0'
			
//			DecimalFormat myformat = new DecimalFormat("0");
//			String num = myformat.format(cell.getNumericCellValue()); 
//			System.out.println(num); 
//			return String.valueOf(cell.getNumericCellValue());
			DecimalFormat myformat = new DecimalFormat("0");
			double num = new Double((double)cell.getNumericCellValue());
            return String.valueOf(myformat.format(num));

		case 1: // '\001'
		default:
			return cell.getStringCellValue();
		}
	}

	public static void main(String args[]) {
		try {
			resizeImage("C:\\digu.JPG", Config.imageWidth, Config.imageHeight, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
